<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="450">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      class="form-wrap"
      label-width="120px"
    >
      <el-form-item label="任务名称" prop="name">
        <ns-input v-model="formData.name" placeholder="请输入任务名称" />
      </el-form-item>
      <el-form-item label="">
        <el-radio-group v-model="keyType">
          <el-radio label="引用聚类结果">引用聚类结果</el-radio>
          <el-radio label="引用文件组">引用文件组</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="聚类结果" prop="clusterResultIds" v-if="keyType === '引用聚类结果'">
        <el-tree-select
          placeholder="请选择聚类结果"
          v-model="formData.clusterResultIds"
          :load="handleLoad"
          value-key="id"
          node-key="id"
          :props="treeProps"
          :default-expanded-keys="expandedKeys"
          style="width: 100%"
          multiple
          lazy
          show-checkbox
        />
      </el-form-item>
      <el-form-item label="文件组" prop="fileManageGroupIds" v-else-if="keyType === '引用文件组'">
        <el-tree-select
          style="max-width: 400px; width: 100%"
          ref="treeGroupRef"
          v-model="formData.fileManageGroupIds"
          multiple
          show-checkbox
          value-key="id"
          node-key="id"
          :data="treeGroupData"
          :props="{ label: 'name' }"
          :render-after-expand="false"
          placeholder="请选择文件组"
          :default-expanded-keys="['0']"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import { createKeywordTask, updateKeywordTask, getKeywordTask } from '@/api/develop/keywordTask'
import { useSelectData } from './useSelectData'
import { useGroupTree } from '@/hooks/web/useFileTree'
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('')

const formLoading = ref(false) // 表单的加载中
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const expandedKeys = ref<string[]>([])

const keyType = ref('引用聚类结果')
const { treeGroupData, reFreshTreeData } = useGroupTree()
reFreshTreeData()
const formData = ref({
  id: undefined as string | undefined,
  name: '',
  clusterResultIds: [] as string[],
  fileManageGroupIds: [] as string[]
})

/** 打开弹窗 */
const open = async (id?: string) => {
  dialogTitle.value = id ? '编辑' : '新增'
  dialogVisible.value = true

  if (id) {
    const res = await getKeywordTask(id)
    formData.value.id = id
    formData.value.name = res.name
    keyType.value = res.clusterResultInfo ? '引用聚类结果' : '引用文件组'
    formData.value.clusterResultIds = res.clusterResultInfo?.map((i: any) => i.id) || []
    formData.value.fileManageGroupIds = res.fileManageGroupInfo?.map((i: any) => i.id) || []
    expandedKeys.value = [...new Set(res.clusterResultInfo?.map((i: any) => i.taskId))] as string[]
  }
}

const formRules = reactive({
  name: [{ required: true, message: '任务名称不能为空', trigger: ['blur', 'change'] }],
  clusterResultIds: [{ required: true, message: '请选择聚类结果', trigger: ['change'] }],
  fileManageGroupIds: [{ required: true, message: '请选择文件组', trigger: ['change'] }]
})
const formRef = ref<FormInstance>() // 表单 Ref

const { treeProps, handleLoad, taskList } = useSelectData()

defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef.value) return
  const valid = await formRef.value?.validate()
  // 提交请求
  if (valid) {
    formLoading.value = true
    const taskIds = taskList.value.map((i: any) => i.id) //任务Id
    const _ids = formData.value.clusterResultIds?.filter((id) => !taskIds.includes(id)) // 把父级id（任务id）过滤掉，只剩下结果id

    const _formData = {
      ...toRaw(formData.value),
      clusterResultIds: _ids,
      fileManageGroupIds: formData.value.fileManageGroupIds
    }
    keyType.value === '引用聚类结果'
      ? (_formData.fileManageGroupIds = [])
      : (_formData.clusterResultIds = [])
    try {
      if (!!formData.value.id) {
        // 编辑
        await updateKeywordTask(_formData)
        message.success(t('common.updateSuccess'))
      } else {
        //新增
        await createKeywordTask(_formData)
        message.success(t('common.createSuccess'))
      }
      closeDialog()
      // 发送操作成功的事件
      emit('success')
    } finally {
      formLoading.value = false
    }
  }
}

const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调

/** 重置表单 */
const resetForm = () => {
  formLoading.value = false

  formData.value = {
    id: undefined,
    name: '',
    clusterResultIds: [],
    fileManageGroupIds: []
  }
  expandedKeys.value = []
  formRef.value?.resetFields()
}

function closeDialog() {
  dialogVisible.value = false
}

watch(dialogVisible, (show) => {
  !show && resetForm()
})
</script>
<style lang="scss" scoped></style>
